import Axios from 'axios'
import { message } from 'ant-design-vue'
import { getToken } from './auth'

// const baseURL = process.env.VUE_APP_BASE_URL
const axios = Axios.create({
  // baseURL,
  timeout: 40000,
})
if (process.env.VUE_APP_SDK === 'chatSdk') {
  axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
}
// 允许携带cookie
axios.defaults.withCredentials = false
// 请求头信息
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
// 默认使用 application/json 形式
axios.defaults.headers.post['Content-Type'] = 'application/json'
// 请求拦截器
axios.interceptors.request.use(
  (res) => {
    const token = getToken()
    if (token) {
      res.headers['Access-Token'] = `${token}`
    }
    return res
  },
  (err) => Promise.reject(err),
)
// 响应拦截器
axios.interceptors.response.use(
  (res) => res,
  async (err) => {
    if (err.response && err.response.data) {
      const code = err.response.status
      const msg = err.response.data.error
      if (code === 409 || code === 1001 || err.response.data.code) {
        return err.response
      } else {
        message.error(` ${msg}`) //Code: ${code}, Message:
      }
    } else {
      message.error(`${err}`)
    }
    return Promise.reject(err)
  },
)

export default axios.request
